package models

import (
	"errors"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"project/jwt-prac/db"
)

type UserLogin struct {
	Username string `form:"username" binding:"required,max=20,printascii,validateUsername"`
	Password string `form:"password" binding:"required,min=8,max=16,excludes= ,printascii,validatePasswd"`
}

func CheckUserLogin(loginSpec *UserLogin) (int, error) {
	var (
		userFromDB User
	)
	//查询用户信息
	err := db.DB.Where("username = ?", loginSpec.Username).Take(&userFromDB).Error
	if err == gorm.ErrRecordNotFound {
		return 400, errors.New("未注册该用户")
	} else if err != nil {
		return 500, err
	}

	//密码比对
	if err = bcrypt.CompareHashAndPassword([]byte(userFromDB.PasswordHash),
		[]byte(loginSpec.Password)); err != nil {
		return 400, err
	}
	//密码比对成功
	return 200, nil
}
